#include <iostream>
#include <vector>
#include <algorithm>

// 前向声明
class Observer;

// 主题接口（Subject）
class Subject {
public:
    virtual void attach(Observer* observer) = 0;
    virtual void detach(Observer* observer) = 0;
    virtual void notify() = 0;
};

// 观察者接口（Observer）
class Observer {
public:
    virtual void update(const std::string& message) = 0;
};

// 具体主题类（ConcreteSubject）
class ConcreteSubject : public Subject {
private:
    std::string state;
    std::vector<Observer*> observers;

public:
    void setState(const std::string& newState) {
        this->state = newState;
        notify();  // 状态变化后通知所有观察者
    }

    void attach(Observer* observer) override {
        observers.push_back(observer);
    }

    void detach(Observer* observer) override {
        observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
    }

    void notify() override {
        for (auto* obs : observers) {
            obs->update(state);  // 通知所有观察者当前状态
        }
    }
};

// 具体观察者类（ConcreteObserver）
class ConcreteObserver : public Observer {
private:
    std::string name;

public:
    ConcreteObserver(const std::string& name) : name(name) {}

    void update(const std::string& message) override {
        std::cout << "Observer [" << name << "] received message: " << message << std::endl;
    }
};
int main() {
    ConcreteSubject subject;

    ConcreteObserver observer1("Observer 1");
    ConcreteObserver observer2("Observer 2");

    // 注册观察者
    subject.attach(&observer1);
    subject.attach(&observer2);

    // 改变主题状态，触发通知
    subject.setState("Hello Observers!");

    // 移除一个观察者
    subject.detach(&observer1);

    // 再次改变状态
    subject.setState("Only Observer 2 should see this.");
}